package com.test.p99other.producerconsumer.example02;

import java.util.Random;
import java.util.concurrent.BlockingQueue;

class Consumer implements Runnable {
    protected BlockingQueue<Object> queue;
    Consumer(BlockingQueue<Object> theQueue) {
        this.queue = theQueue;
    }

    public void run() {
        try {
            while (true)
            {
                Object obj = queue.take();
                try {
                    take(obj);
                } catch (Exception e) {
                    queue.add(obj);
                    System.out.println(Thread.currentThread().getName() + ": return object " + obj);
                }
                if (queue.size() == 0) {
                    break;
                }
            }
        }
        catch (InterruptedException ex) {
            System.out.println("CONSUMER INTERRUPTED");
        }
    }

    void take(Object obj) throws Exception {
        try {
            // simulate time passing
            Thread.sleep(100);
            // simulate throw exception
        } catch (InterruptedException ex) {
            System.out.println("Consumer Read INTERRUPTED");
        }
        int i = new Random().nextInt(2);
        if (i==1) {
            throw new Exception("error");
        }
        System.out.println(Thread.currentThread().getName() + ":Consuming object " + obj);
    }

}